import { isValidElement, cloneElement, useContext, useEffect } from 'react'
import Layout from './FormItemCommon/Layout'
import FormContext from './useForm/FormContext'
import useCreation from '@/hooks/useCreation'
import useUpdate from '@/hooks/useUpdate'
import type { ReactElement, ReactNode } from 'react'

interface FormItemProps {
	label?: string
	name?: string
	tooltip?: string
	children?: ReactNode
	[key: string]: any
}

const formItem = (props: FormItemProps) => {
	const { children, name } = props
	const update = useUpdate()

	const contextValue = useContext(FormContext)
	const { getFieldValue, dispatch, registerField, unRegisterField } = contextValue

	// const updateChange = useCreation(() => {
	// 	return {
	// 		updateValue: () => update()
	// 	}
	// }, [contextValue])

	// useEffect(() => {
	// 	// 注册
	// 	name && registerField(name, { updateValue: () => update() })
	// 	return () => {
	// 		//卸载
	// 		name && unRegisterField(name)
	// 	}
	// }, [contextValue])

	let childrenPro
	if (isValidElement(children) && name) {
		childrenPro = cloneElement(children as ReactElement, {
			value: getFieldValue(name),
			onChange: (v: any) => {
				const payload: any = {}

				// 判断属于那种
				// const value = v?.target?.localName === 'input' ? v?.target?.value : v
				payload[name] = v?.target?.value

				// 更新 store 中的值
				dispatch({ type: 'updateValue', name, value: v?.target?.value })
			}
		})
	} else {
		childrenPro = children
	}

	return <Layout {...props}>{childrenPro}</Layout>
}

export default formItem
